package cn.wolfcde.luowowo.website.web.intercepter;

import cn.wolfcde.luowowo.website.annotation.LoginRequired;
import cn.wolfcde.luowowo.website.util.CookieUtil;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = CookieUtil.getToken(request, response);

        UserInfo userInfo = userInfoRedisService.getLoginUserInfoByToken(token);

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod method = (HandlerMethod) handler;

        if (method.hasMethodAnnotation(LoginRequired.class)) {

            if (userInfo == null) {

                response.sendRedirect("/login.html");

                return false;

            }

        }

        request.getSession().setAttribute("userInfo",userInfo);

        return true;
    }
}
